//pages/seltelcommunity/seltelcommunity.js
//获取应用实例
var Ajax = require('../../utils/Ajax.js')
var utils = require('../../utils/util.js');
var config = require('../../base.conf.js').config;
const app = getApp();
var ctimeout = null;
Page({
  data: {
    imgurl: app.getApi('download'),
    queryname: '',
    userInfo: "",
    nogoodsH:496,
    quartersName:'',
    tapinput:false,
    similarArr:[],
    nearObj: {
      name: '上海市'
    },
    certArr: [],
    resultsArr: [],
    nearArr: [],
  },
  onLoad: function(option) {
    this.setData({
      model: app.globalData.model,
      option
    })
    const sysInfo = wx.getSystemInfoSync();
    const screenWidth = sysInfo.screenWidth;
    this.factor = screenWidth / 750;
  },
  onShow() {
    this.refresh();
  },
  onReady(){
    var query = wx.createSelectorQuery();
    query.select('.pages').boundingClientRect((rect) => {
      this.setData({
        nogoodsH: (rect.height/this.factor)-68-60, 
      })
    }).exec();
  },
  refresh() { //刷新
    this.setData({
      userInfo: utils.getUserInfo()
    }, () => {
      this.getLocation();
      this.data.userInfo && this.getAllQuartersByUserId();
    })
    this.getQuartersByCityName();
  },
  delText(e) { //清空input
    this.setData({
      ['' + e.detail]: '',
      tapinput: false,
    })
  },
  onCertification(e){
    var { item, name}=e.currentTarget.dataset;
     var pages=getCurrentPages();//所有页面栈
     var parent = pages[pages.length - 2];//上一个页面
     var seltelxq = pages[pages.length - 3];//前面第三个页面
    if (name !="cert"&&parent && parent.route == "pages/certification/certification") {
      parent.setData({
        nearObj:item
      },()=>{
        wx.navigateBack()
      })
    } else if (name != "cert"){
      var { nearObj, userInfo} = this.data;
      if (userInfo){//是否用户信息
        wx.redirectTo({
          url: `/pages/certification/certification?` + utils.queryconcat(item),
        })
      }else{
        wx.redirectTo({
          url: `/pages/bindingphone/bindingphone?` + utils.queryconcat(item)
        }) 
      }
    }else{
      if (parent && parent.route == "pages/index/index") {
        parent.setData({
          currentQuarters: item
        }, () => {
          app.saveSync('lastopenId', item.requId);
          wx.navigateBack()
        })
      }
    }
  },
  bindinputval(){
    
  },
  getQuartersByCityName() {//根据城市名小区名搜索小区
    var {
      quartersName,
      nearObj,
      certArr
    } = this.data;
      Ajax.get('getQuartersByCityName', {
        cityName: nearObj.name,
        quartersName: quartersName||''
      }).then((d) => {
        if (d.status == 200 || d.status == 500) {
          var list = d.data || [];
          this.setData({
            resultsArr: d.data || [],
            similarArr: d.data||[],
            quartersName:'',
            statusType: list.length > 0 ? 'none' : 'empty',
          })
        } else {
          var { resultsArr}=this.data;
          this.setData({
            statuserro: resultsArr.length > 0 ? false : true,
            statusType: resultsArr.length > 0 ? 'none' : 'empty',
          })
          utils.showtoast(d.message||'服务器错误,请检查您的网络')
        }
      }).catch((e) => {
        console.log(e)
        var { resultsArr } = this.data;
        this.setData({
          statuserro: resultsArr.length > 0 ? false : true,
          statusType: resultsArr.length > 0 ? 'none' : 'empty',
        })
        utils.showtoast('网络错误,请检查您的网络')
      })
  },
  listNew() {//查询附近的小区
    var {
      latitude,
      longitude,
      userInfo
    } = this.data;
    Ajax.post('listNew', {
      latitude,
      longitude,
      userId: userInfo && userInfo.id || ''
    }).then((d) => {
      if (d.status == 200 && d.data) {
        this.setData({
          nearArr: d.data.rows || []
        })
      } else {
        // utils.showtoast(d.msg || '定位失败,网络错误')
      }
    }).catch((e) => {
      // utils.showtoast('定位失败,网络错误')
    })
  },
  getAllQuartersByUserId() { //查询已认证的小区
    var {
      userInfo,
    } = this.data;
    Ajax.get("getAllQuartersByUserId", {
      userId: userInfo.id
    }).then((d) => {
      // 返回的小区列表为空  
      if (d.status == 200) {
        var list = d.data || [];
        this.setData({
          certArr: list,
        })
      } else {
        utils.showtoast(d.message || '服务器出错')
      }
    }).catch((e) => {
      console.log(e)
    })
  },
  tapinput(){
    var { resultsArr, similarArr}=this.data;
     this.setData({
       tapinput:true,
       similarArr: similarArr.length >0 ? similarArr:resultsArr,
     })  
  },
  bindinputval(e) { //问题描述输入的字符控制
    var {
      name
    } = e.currentTarget.dataset;
    var { resultsArr}=this.data;
    var val = e.detail.value;
    val = val.replace(/\s+/g, "");
    this.setData({
      [name]: val
    },()=>{
      var arr = [] // 临时数组 用于存放匹配的数组
      for (let i in resultsArr) {
        if (resultsArr[i].quartersName.indexOf(val) >= 0) {
          arr.push(resultsArr[i])
        }
      }
      if (arr.length == 0) {
        this.setData({
          similarArr: resultsArr,
        })
      } else {
        this.setData({
          similarArr: arr,
        })
      } 
    })
  },
  selectCity() {
    var {
      nearObj
    } = this.data;
    utils.toPage(`/pages/changcity/changcity?city=${nearObj.name}`)
  },
  onReachBottom: function() {},
  onPullDownRefresh: function() {
    this.refresh()
  },
  //没有UID弹窗
  shownoUidModal(id) {
    var modal = this.selectComponent("#" + id || 'noUid');
    modal.show();
  },
  closeModal(e) { //关闭弹窗
    var id = this.onSetid(e);
    var modal = this.selectComponent("#" + (id || 'modal'));
    modal.hide();
  },
  onSetid(e) { //弹出窗的ID获取
    var id = 'modal'
    if (typeof(e) == 'string') {
      id = e
    } else {
      id = e && (e.currentTarget.id || e.currentTarget.dataset.id);
    }
    return id;
  },
  isopenLocation(){
    wx.authorize({
      scope: "scope.userLocation",
      success: (res) => {
        this.getLocation();
      },
      fail: (e) => {
        // wx.openSetting({
        //   fail(e){
        //     console.log(e)
        //   }
        // });
        wx.showModal({//必须手动点击
          title: '邻里邻外',
          content: '“邻里邻外“需要获取您的地理位置',
          complete: e => {
            utils.hideLoading();
            if (e.confirm) {
              wx.openSetting({
                success:d=>{
                  if (d.authSetting["scope.userLocation"]){
                    this.getLocation();
                  }else{
                    utils.showtoast('获取地理位置失败,请重新获取');
                  }
                },
                fail:e=>{
                  utils.showtoast('获取地理位置失败,请重新获取');
                }
              });
            } else {
              utils.showtoast('获取地理位置失败,请重新获取');
            }
          }
        })
      }
    })
  },
  getLocation() {
    wx.getLocation({
      success: (res) => {
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude
        }, () => {
          this.listNew()
        })
      }
    })
  },
  onShareAppMessage(e) {
    return {
      title: '邻里邻外',
      path: `/pages/index/index`,
    }
  }
})